package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.feign.HotalFeign;
import com.qf.entity.Orders;
import com.qf.entity.Room;
import com.qf.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private HotalFeign hotalFeign;

    /**
     * 请求支付宝 - 生成支付订单
     */
    @RequestMapping("/alipay")
    public void alipay(String oid, HttpServletResponse response){
        System.out.println("进行支付的订单号：" + oid);
        Orders orders = ordersService.getById(oid);

        Room room = hotalFeign.getRoomById(orders.getRid()).getData();

        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2016073000127352",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCxdJ+jfAh2Drf9CUpfI5Gu6+m9bhhnhNUEkDPsfkdn3Hy1R3k0COgTsE/7qiKkuFuAZnhSjNEfYI9LPFeceP0wxMUZcCHq2RxsbhsGNYGe48VRfeHPT0DKeox8pwPN4qcRk7WfoLKUjn67YL9nSjehJCKVav6plXeYkB4U5lCjr64QBPbBVPRIxP0PED1JrIFAoncXLAWQmvNxM6U5rydSB7mpQxY1plvJZ+Hrr7ZkGwT8AX+mrEXYcXnUAANDk5TZ86xWYNu7xZ0CisepIpwx7iQmdMt59GRGy/ayv+9JedpzhoIlUpC8pbsDeE2qcwMor+8tOJnUNeRzH6Jg2f6vAgMBAAECggEALNWYV8fIo3tIhQfJ4IuuDRHRtmiQhecLouGEHOYyyEz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n24nP8OMl7GfBhdv5VZvky0snpV2+jz4ex06wIibe2j/SsdlgLB01gHK5KyP7noyitpMAklx9qrg/eEJ22zpfAFtm6ekMv92TPS5rV78=",
                "json",
                "UTF-8",
                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB",
                "RSA"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://www.baidu.com");//同步响应url，支付完成后页面跳转到哪里？ - 可以设置成自己的首页
        alipayRequest.setNotifyUrl("http://verygoodwlk.xicp.net/pay/result");//异步响应url，支付宝将支付结果告知到哪里？
        //请求的业务主体
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"" + oid + "\"," +
                " \"total_amount\":\"" + orders.getAllPrice().doubleValue() +"\"," +
                " \"subject\":\"" + room.getTitle() + "\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            //根据支付请求申请支付页面
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收支付宝支付的结果接口
     */
    @PostMapping("/result")
    public String payResult(HttpServletRequest request){
        System.out.println("接收到支付宝支付的结果请求！");

        //获得请求所有参数的map集合 ?name=xiaoming&name=xiaohong
        Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, String> paramsMap = new HashMap<>();//将异步通知中收到的所有参数都存放到map中
        System.out.println("支付宝返回的所有参数：-----------------");
        parameterMap.entrySet().stream().forEach(entry -> {
            paramsMap.put(entry.getKey(), entry.getValue()[0]);
            System.out.println(entry.getKey() + "  " + entry.getValue()[0]);
        });
        System.out.println("支付宝返回的所有参数：-----------------");


        boolean signVerfied = false; //调用SDK验证签名
        try {
            signVerfied = AlipaySignature.rsaCheckV1(
                    paramsMap,
                    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB",
                    "UTF-8",
                    "RSA");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(signVerfied){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println("验签成功！进行二次验签！");

            //接收到订单号
            String outTradNo = paramsMap.get("out_trade_no");
            Orders orders = ordersService.getById(outTradNo);
            if (orders != null) {
                double totalAmount = Double.parseDouble(paramsMap.get("total_amount"));
                if (totalAmount == orders.getAllPrice().doubleValue()) {
                    //金额能匹配上
                    String appId = paramsMap.get("app_id");
                    if (appId.equals("2016073000127352")) {

                        //判断支付状态
                        //二次验签完成
                        System.out.println("二次验签通过，修改订单状态！");
                        orders.setStatus(1);
                        ordersService.updateById(orders);

                        return "success";
                    }
                }
            }
        }

        System.out.println("验签失败，当前请求可能不是支付宝发送的请求！");
        //返回失败
        return "failure";
    }
}
